﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using RemoteTool.Common;
using RemoteTool.Shared;
using RemoteToolData.Data;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RemoteTool.Server.Controllers.API
{
    public class TokenRequest
    {
        public string? UserName { get; set; }
        public string? Password { get; set; }
    }

    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RemoteToolController : ControllerBase
    {
        private readonly ILogger<RemoteToolController> logger;
        private readonly UserManager<ApplicationUser> userManager;
        private readonly SignInManager<ApplicationUser> signInManager;
        private readonly ApplicationDbContext applicationDbContext;
        private readonly IConfiguration configuration;

        public RemoteToolController(ILogger<RemoteToolController> logger, UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager, ApplicationDbContext applicationDbContext, IConfiguration configuration)
        {
            this.logger = logger;
            this.userManager = userManager;
            this.signInManager = signInManager;
            this.applicationDbContext = applicationDbContext;
            this.configuration = configuration;
        }

        //GET: api/<RemoteToolController>

        [HttpGet]
        public IEnumerable<string> GetValue()
        {
            return new string[] { "value1", "value2" };
        }


        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> GetToken([FromBody] TokenRequest request)
        {
            var res = new ApiResult<string>() { statusCode = (int)ApiEnum.Error, success = false };
            // 验证用户名密码
            var user = await userManager.FindByNameAsync(request.UserName);
            if (user == null)
            {
                res.message = $"找不到用户{request.UserName}";
                return new JsonResult(res);
            }
            var result = await signInManager.PasswordSignInAsync(user, request.Password, true, false);
            if (result.Succeeded)
            {
                var config = configuration.GetSection("JwtTokenConfig").Get<JwtTokenConfig>();
                var token = JwtHelper.GeneratorToken(request.UserName, config);
                return Ok(token);
            }
            else
            {
                res.message = $"用户密码验证失败{request.Password}";
            }
            return new JsonResult(res);
        }

        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpPost]
        public async Task<IActionResult> GetUserInfo(string userName)
        {
            var res = new ApiResult<UserInfo>() { statusCode = (int)ApiEnum.Error, success = false };
            // 验证用户名密码
            var user = await userManager.FindByNameAsync(userName);
            if (user == null)
            {
                res.message = $"找不到用户{userName}";
                return new JsonResult(res);
            }
            else
            {
                res.success = true;
                res.data = new UserInfo()
                {
                    Name = user.UserName,
                    Email = user.Email,
                    Photo = user.Portrait,
                };
            }
            return new JsonResult(res);
        }

        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpPost]
        public async Task<IActionResult> AddDeviceInfo(DeviceInfo info)
        {
            var res = new ApiResult<DeviceInfo>() { statusCode = (int)ApiEnum.Error, success = false };
            try
            {
                // 查找设备
                var infos = await applicationDbContext.DeviceInfos.ToListAsync();
                var device = infos.Find(p => p.Equals(info) || p.GuidCode == info.GuidCode);
                if (device == null)
                {
                    applicationDbContext.DeviceInfos.Add(info);
                    applicationDbContext.SaveChanges();
                    res.success = true;
                    res.message = "添加成功";
                }
                else
                {
                    res.message = "已经存在该远程设备";
                    res.data = device;
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"添加设备信息发生异常->{ex.Message}");
            }
            return new JsonResult(res);
        }

        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpPost]
        public async Task<IActionResult> DeleteDeviceInfoById(int id)
        {
            var res = new ApiResult<DeviceInfo>() { statusCode = (int)ApiEnum.Error, success = false };
            try
            {
                // 查找设备
                var device = await applicationDbContext.DeviceInfos.FindAsync(id);
                if (device == null)
                {
                    res.message = $"找不到id={id}的设备";
                    return new JsonResult(res);
                }
                else
                {
                    res.data = device;
                    applicationDbContext.DeviceInfos.Remove(device);
                    applicationDbContext.SaveChanges();
                    res.message = $"id={id}的设备删除成功";
                    res.success = true;
                }
            }
            catch (Exception ex)
            {
                res.message = $"删除id={id}的设备信息发生异常->{ex.Message}";
                logger.LogError(ex, $"删除id={id}的设备信息发生异常->{ex.Message}");
            }

            return new JsonResult(res);
        }
        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpPost]
        public async Task<IActionResult> DeleteDeviceInfo(string guidCode)
        {
            var res = new ApiResult<DeviceInfo>() { statusCode = (int)ApiEnum.Error, success = false };
            try
            {
                // 查找设备
                var device = await applicationDbContext.DeviceInfos.Where(p => p.GuidCode == guidCode).FirstOrDefaultAsync();
                if (device == null)
                {
                    res.message = $"找不到guidCode={guidCode}的设备";
                    return new JsonResult(res);
                }
                else
                {
                    res.data = device;
                    applicationDbContext.DeviceInfos.Remove(device);
                    applicationDbContext.SaveChanges();
                    res.message = $"guidCode={guidCode}的设备删除成功";
                    res.success = true;
                }
            }
            catch (Exception ex)
            {
                res.message = $"删除guidCode={guidCode}的设备信息发生异常->{ex.Message}";
                logger.LogError(ex, $"删除guidCode={guidCode}的设备信息发生异常->{ex.Message}");
            }

            return new JsonResult(res);
        }
        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpPost]
        public async Task<IActionResult> ModifyDeviceInfo(DeviceInfo info)
        {
            var res = new ApiResult<DeviceInfo>() { statusCode = (int)ApiEnum.Error, success = false };
            try
            {
                // 查找设备
                var device = await applicationDbContext.DeviceInfos.Where(p => p.GuidCode == info.GuidCode).FirstOrDefaultAsync();
                if (device == null)
                {
                    res.message = $"找不到设备{info}";
                    return new JsonResult(res);
                }
                else
                {
                    device.ToDeskId = info.ToDeskId;
                    device.ToDeskPsw = info.ToDeskPsw;
                    device.ToDeskCount = info.ToDeskCount;
                    device.OraySunId = info.OraySunId;
                    device.OraySunPsw = info.OraySunPsw;
                    device.OraySunCount = info.OraySunCount;
                    device.ProjectName = info.ProjectName;
                    device.ServiceInfo = info.ServiceInfo;
                    device.ServiceIp = info.ServiceIp;
                    device.RemarkInfo = info.RemarkInfo;
                    device.DeviceName = info.DeviceName;
                    device.DeviceSerialNo = info.DeviceSerialNo;
                    device.DeviceSetting = info.DeviceSetting;
                    device.CreatorName = info.CreatorName;
                    applicationDbContext.SaveChanges();
                    res.message = $"guidCode={info.GuidCode}的设备更新成功";
                    res.success = true;
                    res.data = info;
                }
            }
            catch (Exception ex)
            {
                res.message = $"修改guidCode={info.GuidCode}的设备信息发生异常->{ex.Message}";
                logger.LogError(ex, $"修改guidCode={info.GuidCode}的设备信息发生异常->{ex.Message}");
            }
            return new JsonResult(res);
        }
        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpPost]
        public async Task<IActionResult> SearchDeviceInfo(string keyword)
        {
            List<DeviceInfo> list = new List<DeviceInfo>();
            var res = new ApiResult<List<DeviceInfo>>() { statusCode = (int)ApiEnum.Error, success = false };
            try
            {
                var keys = keyword.Split(new string[] { " ", ":", "：", "|" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                if (keys.Count() > 1)
                {
                    list = await applicationDbContext.DeviceInfos
                             .Where(p => p.ProjectName.Contains(keys[0]) || p.DeviceName.Contains(keys[1]))
                             .OrderByDescending(p => p.LastTime).ToListAsync();
                }
                else
                {
                    list = await applicationDbContext.DeviceInfos
                        .Where(p => p.ProjectName.Contains(keys[0]) || p.DeviceName.Contains(keys[0]))
                        .OrderByDescending(p => p.LastTime).ToListAsync();
                    res.data = list;
                }
                if (list?.Count() > 0)
                {
                    res.success = true;
                    res.data = list;
                }
                else
                {
                    res.message = $"找不到关键字为{keyword}的设备";
                }
            }
            catch (Exception ex)
            {
                res.message = $"查询关键词为->{keyword}的设备信息发生异常->{ex.Message}";
                logger.LogError(ex, $"查询关键词为->{keyword}的设备信息发生异常->{ex.Message}");
            }

            return new JsonResult(res);
        }
        /// <summary>
        /// 客户端查询所有的设备信息
        /// </summary>
        /// <returns></returns>
        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpPost]
        public async Task<IActionResult> DownloadDeviceInfos()
        {
            List<DeviceInfo> list = new List<DeviceInfo>();
            var res = new ApiResult<List<DeviceInfo>>() { statusCode = (int)ApiEnum.Error, success = false };
            try
            {
                list = await applicationDbContext.DeviceInfos.ToListAsync();
                if (list?.Count() > 0)
                {
                    res.success = true;
                    res.data = list;
                }
                else
                {
                    res.message = $"找不到设备信息记录";
                }
            }
            catch (Exception ex)
            {
                res.message = $"下载设备信息发生异常->{ex.Message}";
                logger.LogError(ex, $"下载设备信息发生异常->{ex.Message}");
            }

            return new JsonResult(res);
        }
        /// <summary>
        /// 设备端上传本地记录的设备信息
        /// </summary>
        /// <param name="deviceInfos"></param>
        /// <returns></returns>
        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpPost]
        public async Task<IActionResult> UploadDeviceInfos(List<DeviceInfo> deviceInfos)
        {
            var res = new ApiResult<string>() { statusCode = (int)ApiEnum.Error, success = false };
            try
            {
                // 查找设备
                var infos = await applicationDbContext.DeviceInfos.ToListAsync();
                var listAdd = new List<string>();
                var listExist = new List<string>();
                foreach (var info in deviceInfos)
                {
                    var device = infos.Find(p => p.Equals(info) || p.GuidCode == info.GuidCode);
                    if (device == null)
                    {
                        info.Id = 0;
                        applicationDbContext.DeviceInfos.Add(info);

                        res.success = true;
                        listAdd.Add(info.GuidCode);
                    }
                    else
                    {
                        listExist.Add(device.GuidCode);
                    }
                }
                res.message = $"成功添加{listAdd.Count}个设备，已存在{listExist.Count}个设备";
                res.data = JsonConvert.SerializeObject(new { listAdd = listAdd, listExist = listExist });
                applicationDbContext.SaveChanges();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"添加设备信息发生异常->{ex.Message}");
            }
            return new JsonResult(res);
        }

    }
}
